// pages/productDetails/productDetails.js
const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    numbers: 1,
    modifyPriceCol: true,
    share: 1,
    cartCount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu() // 隐藏分享按钮

    if (options.sku_code) {
      this.setData({
        sku_code: options.sku_code
      })
    }

    if (options.source) {
      this.setData({
        source: options.source
      })
    }

    if (options.hidden) {
      this.setData({
        hidden: options.hidden
      })
    }

    if (options.inn_id) {
      this.setData({
        inn_id: options.inn_id
      })
    }

    if (options.q) {
      var link = options.q;
      link = unescape(decodeURI(link));
      var num = link.indexOf("?");
      link = link.substring(num + 1);
      var ary = link.split("&");
      var obj = {}
      for (var i = 0; i < ary.length; i++) {
        var key = ary[i].split("=")[0];
        var value = ary[i].split("=")[1];
        obj[key] = value
      }
      this.setData(obj)
    }

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.userStatus();
    this.getProductInfo();
    this.cartNum();
  },

  //购物车商品数量
  cartNum: function () {
    var that = this;
    api.POST({
      params: '',
      url: app.globalData.base_url + 'shoppingcart/countGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          // util.showSuccess("加入成功")
          // console.log(res)
          that.setData({
            cartCount: res.data.data.countNum
          })
        }

      },
      fail: function (fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },

  //获取个人状态详情
  userStatus: function (e) {
    var that = this;
    api.POST({
      params: "",
      url: app.globalData.base_url + 'user/status',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          app.globalData.userStatus = res.data.data
          that.setData({
            avatar: res.data.data.avatar,
            nickname: res.data.data.nickname,
            user_flag: res.data.data.user_flag,
            audit_status: res.data.data.audit_status || null,
            unread: res.data.data.unread
          })
        }
      },
      fail: function (fail) {
        util.showError("网络 错误");
      }
    })
  },

  getProductInfo: function () {
    var that = this;
    var params = new Object()
    params.inn_id = this.data.inn_id;
    params.sku_code = this.data.sku_code;
    util.showLoading("数据加载中..");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'inn/getGoodsInfo',
      success: function (res) {
        util.hiddenLoading();
        console.log(res.data);
        if (util.isEmpty(res.data.code)) {
          that.setData({
            rawData: res.data.data.goods_info,
            newPrice: res.data.data.current_price,
            inn_info: res.data.data.inn_info
          });
        }

      },
      fail: function (fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },
   //手动输入数量
   inputNumber: function (e) {
      var num = e.detail.value;
      num = num.replace(/^0/g, 1);
      var stock = this.data.rawData.stock;
      if (stock && num != '') {
         if (num >= stock) {
            util.showError("库存不足")
         }
         num <= stock ? num = num : num = stock
      }
      this.setData({
         numbers: num
      })
   },
   //检查输入数量是否为空
   checkInputNumber: function () {
      var num = this.data.numbers;
      var reg = /^\s*$/g;
      if (reg.test(num) || num == null || num == "") {
         this.setData({
            numbers: 1
         })
      }
   },
  addNum: function () {
    var num = this.data.numbers;
    num++;
    this.setData({
      numbers: num
    })
  },
  minusNum: function () {
    var num = this.data.numbers;
    if (num > 1) {
      num--;
    }
    this.setData({
      numbers: num
    })
  },
  // 加入购物车
  addCart: function () {
    var that = this;
    var params = new Object()
    params.sku_code = this.data.sku_code;
    params.num = this.data.numbers;
    if (this.data.inn_id) {
      params.inn_id = this.data.inn_id;
    }
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/addGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          util.showSuccess("加入成功");
        } else {
          util.showStatus(res.data.message)
        }

        that.cartNum();

      },
      fail: function (fail) {
        util.showErrorPath("../../../", "获取失败，请检查网络");
      }
    })
  },
  // 立即购买
  pay: function () {
    var orderList = [];
    var box = new Object();
    box.num = this.data.numbers;
    box.stock = this.data.rawData.stock;
    if (this.data.inn_id) {
      var inn_id = this.data.inn_id;
    }
    if (this.data.uid) {
      var uid = this.data.uid;
    } else {
      var uid = ''
    }

    box.sku_code = this.data.sku_code;
    box.inn_id = this.data.inn_id;
    box.current_price = this.data.rawData.current_price;
    box.gname = this.data.rawData.gname;
    box.image = this.data.rawData.image;
    box.degree = this.data.rawData.degree;
    box.degree_unit = this.data.rawData.degree_unit;
    box.volume = this.data.rawData.volume;
    box.volume_unit = this.data.rawData.volume_unit;
    box.total = (this.data.numbers * this.data.rawData.current_price).toFixed(2);
    orderList.push(box);
    wx.setStorageSync('orderList', orderList);
    if (inn_id) {
      wx.navigateTo({
        url: '/index/pages/order/order?inn_id=' + inn_id
      })
    } else {
      wx.navigateTo({
        url: '/index/pages/order/order'
      })
    }
  },
  linkCart: function () {
    wx.navigateTo({
      url: '/index/pages/cart/cart'
    })
  },
  linkShop: function () {
    var inn_id = this.data.inn_id
    wx.navigateTo({
      url: '/agent/pages/storeGoodsList/storeGoodsList?inn_id=' + inn_id
    })
  },
  onShareAppMessage: function (res) {
    var that = this;
    var sku_code = that.data.sku_code
    var inn_id = that.data.inn_id
    var url = '/agent/pages/storeProductDetail/storeProductDetail?sku_code=' + sku_code + '&inn_id=' + inn_id
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: that.data.rawData.gname,
        path: url,
        imageUrl: that.data.rawData.share_img,
        success: function (res) {
          // 转发成功
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }
  },
  modifyPrice: function () {
    this.setData({
      modifyPriceCol: false
    })
  },
  closeModifyPrice: function () {
    this.setData({
      modifyPriceCol: true
    })
  },
  newPrice: function (e) {
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    var money = e.detail.value / 1
    var newPrice = this.data.newPrice / 1
    var current_price = this.data.rawData.current_price / 1
    var minprice = this.data.rawData.share_bottom_price / 1
    if (reg.test(money)) {
      if (money < minprice) {
        money = minprice
      } else if (money > current_price) {
        money = current_price
      }
      money = money.toFixed(2);
    } else {
      money = this.data.newPrice
    }
    this.setData({
      newPrice: money
    })
  }
})